/*
 * ImageCache.cpp
 *
 *   This is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2 of the License, or (at your option) any later version.
 *
 *   This software is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Lesser General Public License for more details.
 *
 *  Created on: 2010-1-2
 *      Author: Huang Haiyang
 */

#include "..\ImageCache.h"

#include <aknutils.h>
#include "utils\ImageUtils.h"

namespace resource
	{
	
	CImageCache* CImageCache::getInstance()
		{
		CImageCache* img = static_cast<CImageCache*>( CCoeEnv::Static(TUid::Uid(EImageCacheUID)) );
		if (!img)
			{
			img = new (ELeave) CImageCache();
			}
		return img;
		}
	
	CImageCache::CImageCache()
		:CCoeStatic(TUid::Uid(EImageCacheUID))
		{

		}

	CImageCache::~CImageCache()
		{
		iCachedImages.ResetAndDestroy();
		}

	TSize CImageCache::GetImageSize(const TDesC& aTag) const
		{
		TSize imageSize;
		data::CPNG* it;
		it = GetCachedImage(aTag);
		if (it && it->iRawFore)
			{
			imageSize = it->iRawFore->SizeInPixels();
			}
		else
			{
			TFileName path;
			FullFillImagePath(path, aTag);
			imageSize = utils::ImageUtils::GetImageSize(path);
			}
		
		return imageSize;
		}
	
	data::CPNG* CImageCache::GetImage(const TDesC& aTag)
		{
		data::CPNG* img;
		img = GetCachedImage(aTag);
		if (!img)
			{
			img = LoadImageToCache(aTag);
			}
	
		return img;
		}
	
	data::CPNG* CImageCache::GetCachedImage(const TDesC& aTag) const
		{
		TInt count = iCachedImages.Count();
		data::CPNG *it = NULL, *tmp;
		
		for (TInt i = 0; i < count; i++)
			{
			tmp = iCachedImages[i];
			if (tmp->iName->Compare(aTag) == 0)
				{
				it = tmp;
				break;
				}
			}
		
		return it;
		}
	
	data::CPNG* CImageCache::LoadImageToCache(const TDesC& aTag)
		{
		TInt err;
		TFileName path;
		data::CPNG* img;
		
		FullFillImagePath(path, aTag);
		
		img = new (ELeave) data::CPNG();
		CleanupStack::PushL(img);
		TRAP(err,
				img->iName = aTag.AllocL(););
		if (err != KErrNone)
			{
			CleanupStack::Pop(img);
			}
		else
			{
			TRAP(err,
					(void)utils::ImageUtils::LoadPNGL(path, *img);
			);
			CleanupStack::Pop(img);
			}
		
		TRAP(err, iCachedImages.AppendL(img););
		
		return img;
		}
	
	void CImageCache::FullFillImagePath(TFileName& aResult, const TDesC& aTag)
		{
		aResult.Copy(_L("\\resource\\apps\\040B7678\\"));
		aResult.Append(aTag);
		CompleteWithAppPath(aResult);
		}
	
	}
